import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from '@/api'

const state = {
  cartList: []
};
const mutations = {
  CARTLIST (state, cartList) {
    state.cartList = cartList
  }
};
const actions = {
  async getCartList ({ commit }) {
    let result = await reqCartList()
    if (result.code == 200) {
      commit('CARTLIST', result.data)
    }
  },
  async deleteCartById ({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId);
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },
  async updateCheckedById ({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked);
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },
  deleteAllCheckedCart ({ dispatch, getters }) {
    let allPromise = [];
    getters.cartList.cartInfoList.forEach(item => {
      let promise = item.isChecked == 1 ? dispatch('deleteCartById', item.skuId) : '';
      allPromise.push(promise)
    })
    return Promise.all[allPromise]
  },
  updateAllCartChecked ({ dispatch, getters }, isChecked) {
    let allPromise = [];
    getters.cartList.cartInfoList.forEach(item => {
      let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked });
      allPromise.push(promise);
    })
    return Promise.all[allPromise]
  }
};
const getters = {
  cartList (state) {
    return state.cartList[0] || {}
  }
};

export default {
  state,
  mutations,
  actions,
  getters
}